package com.example.administrator.mysaft;

import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ProcessmanagerActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView mRunProcessNum;
    private TextView mMemoryTV;
    private TextView mProcessNumTV;
    private ListView mListview;
    private ProcessManagerAdapter adapter;
    private  List<TaskInfo> runningTaskInfo;
    private  List<TaskInfo> userTaskInfos=new ArrayList<>();
    private  List<TaskInfo> sysTaskInfos=new ArrayList<>();
    private  ActivityManager manager;
    private  int runnigPocessCount;
    private  long totalMem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_processmanager);
        initView();
        fillData();
    }



    @Override
    protected void onResume() {
        if (adapter!=null){
            adapter.notifyDataSetChanged();
        }
        super.onResume();
    }

    private void initView() {
        findViewById(R.id.rl_titlebar).setBackgroundColor(getResources().getColor(R.color.light_green));
        ImageView mLeftImgv= (ImageView) findViewById(R.id.imgv_leftbtn);
        mLeftImgv.setOnClickListener(this);
        mLeftImgv.setImageResource(R.drawable.login);

        ImageView mRightImgv= (ImageView) findViewById(R.id.imgv_rightbtn);
        mRightImgv.setOnClickListener(this);
        mRightImgv.setImageResource(R.drawable.setting_icon);

        ((TextView)findViewById(R.id.tv_title)).setText("进程管理");
        mRunProcessNum=(TextView)findViewById(R.id.tv_runningprocess_num);
        mMemoryTV= (TextView) findViewById(R.id.tv_memory_processmanager);
        mProcessNumTV= (TextView) findViewById(R.id.tv_user_runningprocess);
        runnigPocessCount=SystemInfosUtils.getRunningPocessCount(ProcessmanagerActivity.this);

        mRunProcessNum.setText("运行中的进程："+runnigPocessCount+"个");
        long totalAvailMem=SystemInfosUtils.getAvailMem(this);
        totalMem=SystemInfosUtils.getToalMen();
        mMemoryTV.setText("可用/总内存："+Formatter.formatFileSize(this,totalAvailMem)+"/"+ Formatter.formatFileSize(this,totalMem));
        mListview= (ListView) findViewById(R.id.lv_runningapps);
        initListener();

    }

    private void initListener() {
        findViewById(R.id.btn_selectall).setOnClickListener(this);
        findViewById(R.id.btn_select_inverse).setOnClickListener(this);
        findViewById(R.id.btn_cleanprocess).setOnClickListener(this);
        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object object=mListview.getItemAtPosition(position);
                if (object!=null & object instanceof TaskInfo){
                    TaskInfo info=(TaskInfo) object;
                    if (info.packageName.equals(getPackageName())){
                        return;
                    }
                    info.isChecked=!info.isChecked;
                    adapter.notifyDataSetChanged();
                }
            }
        });
        mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                 if (firstVisibleItem>=userTaskInfos.size()+1){
                     mProcessNumTV.setTextColor(Color.WHITE);
                    mProcessNumTV.setText("系统进程："+sysTaskInfos.size()+"个");
                 }else {
                     mProcessNumTV.setTextColor(Color.WHITE);
                     mProcessNumTV.setText("用户进程："+userTaskInfos.size()+"个");
                 }

            }
        });
    }

    private void fillData() {
        userTaskInfos.clear();
        sysTaskInfos.clear();
        new Thread(){
            @Override
            public void run() {
                runningTaskInfo=TaskInfoParser.getRunningTaskInfo(getApplicationContext());
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       for (TaskInfo taskinfo:runningTaskInfo){
                           if (taskinfo.isUserApp){
                               userTaskInfos.add(taskinfo);
                           }else {
                               sysTaskInfos.add(taskinfo);
                           }
                       }
                       if (adapter==null){
                           adapter=new ProcessManagerAdapter(getApplicationContext(),userTaskInfos,sysTaskInfos);
                           mListview.setAdapter(adapter);

                       }else {
                           adapter.notifyDataSetChanged();
                       }
                       if (userTaskInfos.size()>0){
                           mProcessNumTV.setTextColor(Color.WHITE);
                           mProcessNumTV.setText("用户进程："+userTaskInfos.size()+"个");
                       }
                       else {
                           mProcessNumTV.setText("系统进程："+sysTaskInfos.size()+"个");

                       }
                   }
               });
            };
        }.start();
    }
    @Override
    public void onClick(View v) {
switch (v.getId()){
    case R.id.imgv_leftbtn:
        finish();
        break;
    case R.id.imgv_rightbtn:
        startActivity(new Intent(this,ProcessmanagerSettingActivity.class));
        break;
    case R.id.btn_selectall:
        selectAll();
        break;
    case R.id.btn_select_inverse:
        inverse();
        break;
    case R.id.btn_cleanprocess:
        cleanProcess();
        break;
}
    }


    private void cleanProcess() {
        manager= (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        int count=0;
        long saveMemory=0;
        List<TaskInfo> killedtaskInfos=new ArrayList<>();
        for (TaskInfo info:userTaskInfos){
            if (info.isChecked){
                count++;
                saveMemory+=info.appMemory;
                manager.killBackgroundProcesses(info.packageName);
                killedtaskInfos.add(info);
            }
        }
        for (TaskInfo info:sysTaskInfos){
            if (info.isChecked){
                count++;
                saveMemory+=info.appMemory;
                manager.killBackgroundProcesses(info.packageName);
                killedtaskInfos.add(info);
            }
        }
        for (TaskInfo info:killedtaskInfos){
            if (info.isUserApp){
                userTaskInfos.remove(info);

            }else{
                sysTaskInfos.remove(info);
            }
        }
        runnigPocessCount-=count;
        mRunProcessNum.setText("运行中的进程："+runnigPocessCount+"个");
        mMemoryTV.setText("可用内存："+Formatter.formatFileSize(this,SystemInfosUtils.getAvailMem(this))+"/"+Formatter.formatFileSize(this,totalMem));
        Toast.makeText(this,"清理了"+count+"个进程，释放了"+Formatter.formatFileSize(this,saveMemory)+"内存",Toast.LENGTH_LONG).show();
        mProcessNumTV.setText("用户进程："+userTaskInfos.size()+"个");
        adapter.notifyDataSetChanged();
    }
//反选
private void inverse() {
    for (TaskInfo taskinfo:userTaskInfos){
        if (taskinfo.packageName.equals(getPackageName())){
            continue;
        }
        boolean checked=taskinfo.isChecked;
        taskinfo.isChecked=!checked;
    }
    for (TaskInfo taskInfo:sysTaskInfos){
        boolean checked=taskInfo.isChecked;
        taskInfo.isChecked=!checked;
    }
    adapter.notifyDataSetChanged();
}
//    全选

    private void selectAll() {
        for (TaskInfo taskinfo:userTaskInfos){
            if (taskinfo.packageName.equals(getPackageName())){
                continue;
            }
            taskinfo.isChecked=true;
        }
        for (TaskInfo taskinfo:sysTaskInfos){
            taskinfo.isChecked=true;
        }
        adapter.notifyDataSetChanged();
    }

}
